package co.fitstart.api.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.entity.product.Product;
import co.fitstart.entity.product.stat.UserProductBehavior;

/**
 * 
 * @author downpour
 */
@Repository("productDaoSupport")
public class ProductDaoSupport {
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    /**
     * Load user product behavior
     * 
     * @param product
     * @param openid
     * @return
     */
    @SuppressWarnings("unchecked")
    public UserProductBehavior loadUserProductBehavior(Product product, String openid) {
        
        if(StringUtils.isNotBlank(openid)) {
            
            // load user product behavior by product and openid
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("openid", openid);
            parameters.put("product", product);
            
            List<UserProductBehavior> userProductBehaviors = genericDaoSupport.searchForList("FROM UserProductBehavior userProductBehavior WHERE userProductBehavior.openid = :openid AND userProductBehavior.product = :product", parameters);
            
            return userProductBehaviors.size() > 0 ? userProductBehaviors.get(0) : null;
            
        }
        
        return null;
    }
}
